package cn.yeamin.ms.service.impl;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import cn.yeamin.ms.service.support.BaseService;
import cn.yeamin.ms.utils.IsEmptyUtils;
import cn.yeamin.ms.utils.MD5Utils;
import cn.yeamin.ms.vo.Role;
import cn.yeamin.ms.vo.User;

/**
 * @packageName: 包名: cn.yeamin.ms.service.impl
 * @classDesc: 类功能描述:(用户Service)
 * @author: Administrator
 * @createTime: 2017/7/24 16:12
 * @version: v1.0
 * @copyright:奕明(上海)影视传媒有限公司
 */
@Service
@Transactional
public class UserService extends BaseService<User> {

	@Autowired
	private RoleService roleService;
	
	
	public void grant(Long id, Long[] roleIds) {
		if(roleIds == null) {
			roleService.deleteAll(id);
			return;
		}
		User user = queryById(id);
		Assert.notNull(user, "用户不存在");
		Assert.state(!"root".equals(user.getUserName()),"超级管理员用户不能修改管理角色");
		Set<Role> delIds = roleService.findRoleByUserId(id);
		if(!IsEmptyUtils.isEmptyForListOrSet(delIds)) {
			for (Role role : delIds) {
				roleService.deleteGrant(id,role.getId());
			}
		}
		for (Long rid : roleIds) {
			roleService.grant(id,rid);
		}
		
	}

	public void updatePwd(User user,String oldPassword, String password1, String password2) {
		Assert.notNull(user, "用户不能为空");
		Assert.notNull(user.getPassword(), "原始密码不能为空");
		Assert.notNull(password1, "新密码不能为空");
		Assert.notNull(password2, "重复密码不能为空");
		
		Assert.isTrue(user.getPassword().equals(MD5Utils.md5(oldPassword)), "原始密码不正确");;
		Assert.isTrue(password1.equals(password2), "两次密码不一致");
		user.setPassword(MD5Utils.md5(password1));
		this.updateSelective(user);
	}

	

}
